package com.lgmshare.component.app;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Handler;

import androidx.multidex.MultiDexApplication;

import com.lgmshare.component.imageloader.ImageLoader;
import com.lgmshare.component.logger.Logger;
import com.lgmshare.component.storage.DataKeeper;


/**
 * framework of base application class
 *
 * @author: lim.
 * @email: lgmshare@gmail.com
 * @Version V1.0
 * @Description
 * @datetime : 2015/5/11 11:32
 */
public abstract class LaraApplication extends MultiDexApplication {

    protected final String TAG = LaraApplication.this.getClass().getName();

    //以下属性应用于整个应用程序，合理利用资源，减少资源浪费
    private static Context mContext;//上下文
    private static long mMainThreadId;//主线程id
    private static Handler mMainThreadHandler;//主线程Handler

    public static Context getContext() {
        return mContext;
    }

    public static long getMainThreadId() {
        return mMainThreadId;
    }

    public static Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        mMainThreadId = android.os.Process.myTid();
        mMainThreadHandler = new Handler();

        //框架配置项
        LaraConfiguration config = onBuildFrameConfiguration();
        if (config == null) {
            config = new LaraConfiguration.Builder().build();
        }
        LaraConfig.setup(getApplicationContext(), config);
    }

    /**
     * 框架配置
     *
     * @return 框架配置
     */
    public abstract LaraConfiguration onBuildFrameConfiguration();

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Logger.d(TAG, "Configuration Changed");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Logger.e(TAG, "Warning! Memory Cache Low");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        //应用需要释放更多内存空间
        Logger.e(TAG, "onTrimMemory");
        switch (level) {
            case TRIM_MEMORY_RUNNING_LOW:
                ImageLoader.cleanMemory(this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //应用结束时调用
        Logger.d(TAG, "Terminate");
    }
}
